module.exports = (app) => {
    const express = require('express');
    const axios = require("axios")
    const router = express.Router({
        mergeParams: true
    });
    const mongoose = require("mongoose");
    const User = mongoose.model("User");
    const jwt = require('jsonwebtoken');
    const assert = require('http-assert');
    const authMiddleWare = require("../../middleware/auth");
    const Account = mongoose.model("Account");
    const DY = mongoose.model("DY");
    const multer = require('multer');
    const path = require('path');
    const storage = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, 'uploads/video/'); // 上传文件的保存路径
        },
        filename: function(req, file, cb) {
            cb(null, Date.now() + path.extname(file.originalname)); // 以时间戳命名文件
        }
    });
    const storage2 = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, 'uploads/img/'); // 上传文件的保存路径
        },
        filename: function(req, file, cb) {
            cb(null, Date.now() + path.extname(file.originalname)); // 以时间戳命名文件
        }
    });
    const upload = multer({ storage: storage });
    const upload2 = multer({ storage: storage2 });

    const getDate = () => {
        const now = new Date();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份，注意要加1
        const day = String(now.getDate()).padStart(2, '0'); // 日期
        const hours = String(now.getHours()).padStart(2, '0'); // 小时
        const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟
        const seconds = String(now.getSeconds()).padStart(2, '0'); // 秒

        const kDate = `${month}-${day}  ${hours}:${minutes}:${seconds}`;
        return kDate
    }

    // DY start
    router.post("/upload", upload.single('video'), async (req, res) => {
        if (!req.file) {
            res.send({ message: "没有文件上传", success: false });
            return
        }
        const videoDate = getDate()
        const videoUrl = `http://118.25.99.223:3000/uploads/video/${req.file.filename}`;
        await DY.create({ videoUrl, videoDate, phone: "", status: "0", dyHome: "", code: "" });
        res.send({ url: videoUrl, success: true });
    })
    router.post("/uploadimg", upload2.single('file'), async (req, res) => {
        console.log(req.file)
        if (!req.file) {
            res.send({ message: "没有文件上传", success: false });
            return
        }
        const url = `http://118.25.99.223:3000/uploads/img/${req.file.filename}`;
        res.send({ url: url, success: true });
    })
    router.get("/dyAll", async (req, res) => {
        let items = await DY.find();
        items = items.reverse()
        res.send({
            success: true,
            items
        });
    });
    router.post("/delVideoAll", async (req, res) => {
        console.log(req.body)
        await DY.deleteMany({});
        res.send({
            success: true,
        });
    })
    router.post("/delVideo", async (req, res) => {
        let { _id } = req.body
        let items = await DY.deleteOne({ _id });
        res.send({
            success: true,
            items
        });
    });
    router.post("/changeVideoStatus", async (req, res) => {
        const { status, _id } = req.body
        console.log(_id, status)
        const model = await DY.updateOne({ _id: _id }, { $set: { status: status } });
        res.send({ data: model, success: true });
    });
    router.get("/getVideo", async (req, res) => {
        const phone = req.query.dyPhone;
        const init = req.query.init;
        let userVideo = await DY.findOne({ phone });
        if (userVideo || init == 0) {
            res.send({
                success: true,
                code: 210,
                items: userVideo
            });
            return
        }

        const items = await DY.findOne({ status: "0" });
        if (items) {
            const id = items._id
            const model = await DY.updateOne({ _id: id }, { $set: { status: "1", phone } });
            items.status = "1"
            res.send({
                success: true,
                items: items
            });
        } else {
            res.send({
                success: true,
                items: []
            });
        }
    });

    router.post('/userSetVideo', async (req, res) => {
        const { status, _id } = req.body
        let data = req.body
        data.status = "2"
        const model = await DY.updateOne({ _id: _id }, {
            $set:
            {
                status: data.status,
                dyHome: data.dyHome,
                dyCode: data.dyCode
            }
        });
        console.log(data._id)
        res.send({ data: model, success: true });
    });

    // DY end

    router.post('/setStatus', async (req, res) => {
        const { status, id } = req.body
        const model = await Account.updateOne({ _id: id }, { $set: { status: status } });
        res.send({ data: model, success: true });
    });

    // 创建资源
  router.post('/addAccount', async (req, res) => {
      const { username, account, password, payPassword } = req.body
      const kDate = getDate()
      const model = await Account.create({ username, account, password, payPassword, kDate, status: "1" });
      res.send({ data: model, success: true });
    });
    router.get("/queryAccountAll", async (req, res) => {
        let items = await Account.find();
        // items = items.filter(e => {
        //     return e.username == req.body.username
        // })
        items = items.reverse()
        res.send({
            success: true,
            items
        });
    });
    // 读取资源列表
    router.get("/queryAccount", async (req, res) => {
        const queryOptions = { username: req.query.username };
        const user = await User.find(queryOptions)
        let items = await Account.find(queryOptions);
        // items = items.filter(e => {
        //     return e.username == req.body.username
        // })
        items = items.reverse()
        res.send({
            success: true,
            user,
            items
        });
    });
  
    // 资源通用接口封装
    app.use(
      "/web/api/rest",
      authMiddleWare(),
      router
    )
  
  // 登录接口
  app.post("/web/api/login", async (req, res) => {
    const { username, password } = req.body
    // 1. 根据用户名找用户
    const User = require("../../models/User")
    const usernameObj = {
      username: username,
    }
    const user = await User.findOne(usernameObj).select("+password")
    if(user == null) {
      res.send({
        success: false,
        message: "用户不存在，此账号非K宝账号，需要额外注册",
      })
      return
    }
    // 2. 校验密码
    const isValid = require("bcryptjs").compareSync(password, user.password)
    assert(isValid, 422, "密码错误")
    // 3. 返回token
    const token = jwt.sign({ id: user._id }, app.get("secret"))
    res.send({
      success: true,
      message: "登录成功！",
      token,
    })
  })

  // 注册接口
  app.post("/web/api/register", async (req, res) => {
      const { username, password, platform } = req.body
      const user = await User.find({ username })
      if (user.length > 0) {
          res.send({
              success: false,
              message: "此账号已经存在！！"
          })
          return
      }
    const reg_phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    // 强密码(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-16之间)：
      // const reg_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/;

    if (!reg_phone.test(username)) {
      res.send({
        success: false,
        message: "请填写正确的手机号码！"
      })
      return
    }

      // if (!reg_password.test(password)) {
      //   res.send({
      //     success: false,
      //     message: "密码格式不正确！必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-16之间"
      //   })
      //   return
      // }

    await User.create({
      username,
        password,
        platform
    })

    res.send({
      success: true,
      message: "注册成功！"
    });
  })


  const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjUyLCJwaWQiOjE0MywidXNlcm5hbWUiOiLlsI_psqTpsbw2Iiwibmlja25hbWUiOiLlsI_psqTpsbw2IiwibGV2ZWwiOjQsImV4cCI6MTcyNDU3NDI5OX0.ydsmhqRAukBIWkAdUCLtG8BjD8inye-L-sukiXTbh1s';
  const url = 'http://159.75.246.216:8003/phone/list?pageNo=1&pageSize=100';
  let getList = async() => {
    return new Promise((resolve, reject) => {
      axios.get(url,{
        headers: {
          'Token': token
        }
      }).then(res => {
        resolve(res.data.result)
      }).catch(err => {
        reject({err, error:true})
      })
    })
  }
  
  router.get("/getsmsList", async (req, res) => {
    let data = await getList()
    if(data.error) {
      res.send({
        success: false,
        data,
        message: "失败"
    });
    }
    let arr= data.records
    arr = arr.filter(e => {
      return e.phone == req.query.phone
    })

    res.send({
        success: true,
        data:arr
    });
  });


  let postphone = async(phones) => {
    return new Promise((resolve, reject) => {
      axios.post('http://159.75.246.216:8003/phone/post',{phones},{
        headers: {
          'Token': token
        }
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject({err, error:true})
      })
    })
  }
  router.post("/postSms", async (req, res) => {
    const { phones } = req.body
      let data = await postphone(phones)
    res.send({
        success: true,
        data
    });
  });


  // 错误处理函数
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
        message: err.message,
    })
  })
}
